<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-card shadow="hover" class="layout-padding-auto create-form">
			<el-form ref="formRef" :model="stateData.vmModel" :rules="formRules" label-width="120px">
				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>单据信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
								<template #label>
									<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.BillCode" clearable class="width100" disabled placeholder="自动生成"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
								<template #label>
									<WtmLabelTooltip label="备注" tooltip="备注" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Remark" clearable class="width100"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>基本信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_PersonId_FormItem"
								prop="Entity.PersonId"
								:rules="[{ required: true, message: '员工为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="员工" tooltip="关联的员工实体" />
								</template>
								<WtmPersonSelector v-model="stateData.vmModel.Entity.PersonId" :prefill-person="stateData.prefillPerson" @change="onPersonSelected" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
								<template #label>
									<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.StaffNo" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
								<template #label>
									<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Name" clearable class="width100" disabled placeholder="选取人员后带入"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>调休申请信息</span>
					</div>

					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_CompOffType_FormItem"
								prop="Entity.CompOffType"
								:rules="[{ required: true, message: '调休类型为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="调休类型" tooltip="正常调休/等时调休" />
								</template>
								<el-select v-model="stateData.vmModel.Entity.CompOffType" clearable class="width100" @change="onCompOffTypeChange">
									<el-option v-for="item in COMP_OFF_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_StartTime_FormItem"
								prop="Entity.StartTime"
								:rules="[{ required: true, message: '开始时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="开始时间" tooltip="开始时间" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.StartTime"
									type="date"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择开始时间"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item
								ref="Entity_EndTime_FormItem"
								prop="Entity.EndTime"
								:rules="[{ required: true, message: '结束时间为必填项', trigger: 'blur' }]"
							>
								<template #label>
									<WtmLabelTooltip label="结束时间" tooltip="结束时间" />
								</template>
								<el-date-picker
									v-model="stateData.vmModel.Entity.EndTime"
									type="date"
									:disabled-date="disabledDate"
									clearable
									class="width100"
									placeholder="请选择结束时间"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Days_FormItem" prop="Entity.Days" :rules="[{ required: true, message: '天数为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="天数" tooltip="天数" />
								</template>
								<el-input v-model="stateData.vmModel.Entity.Days" :disabled="true" class="width100" placeholder="系统自动计算"></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="24" class="mb20" v-if="stateData.vmModel.Entity.CompOffType === '等时调休'">
							<el-form-item ref="Entity_AvailableOvertime_FormItem" prop="Entity.AvailableOvertime">
								<template #label>
									<WtmLabelTooltip label="可用加班记录" tooltip="双击【已调休时长】列输入本次使用时长，调休总时长将自动累加计算" />
								</template>
								<WtmTable
									ref="overtimeTableRef"
									:data="overtimeTableData.data"
									:header="overtimeTableData.header"
									:config="overtimeTableData.config"
									@selection-change="handleOvertimeSelectionChange"
									@cellChange="handleCellChange"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20" v-if="stateData.vmModel.Entity.CompOffType === '等时调休'">
							<el-form-item ref="Entity_CompOffHours_FormItem" prop="Entity.CompOffHours">
								<template #label>
									<WtmLabelTooltip label="调休时长(小时)" tooltip="等时调休使用的小时数" />
								</template>
								<el-input-number
									v-model="stateData.vmModel.Entity.CompOffHours"
									:disabled="true"
									class="width100"
									placeholder="根据已调休时长自动计算"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<el-form-item ref="Entity_Reason_FormItem" prop="Entity.Reason" :rules="[{ required: true, message: '事由为必填项', trigger: 'blur' }]">
								<template #label>
									<WtmLabelTooltip label="事由" tooltip="调休事由" />
								</template>
								<el-input
									v-model="stateData.vmModel.Entity.Reason"
									type="textarea"
									:rows="2"
									clearable
									class="width100"
									placeholder="请输入调休事由"
								></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>

				<div class="form-section">
					<div class="section-title">
						<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
						<span>工作信息</span>
					</div>
					<el-row :gutter="20">
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmOrgSelector
								v-model="stateData.vmModel.Entity.OrgId"
								label="公司"
								prop="Entity.OrgId"
								:auth="false"
								:disabled="true"
								placeholder="选取人员后带入"
							/>
						</el-col>
						<el-col :xs="24" :lg="12" class="mb20">
							<WtmDeptSelector v-model="stateData.vmModel.Entity.GroupId" prop="Entity.GroupId" label="所属部门" :auth="false" :disabled="true" />
						</el-col>
					</el-row>
				</div>
			</el-form>
		</el-card>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.add;false">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, nextTick, watch, type ComponentInternalInstance } from 'vue';
import { SysDailyCompOffRequestBillApi as api } from '/@/views/daily/sysdailycompoffrequestbill/api';
import other from '/@/utils/other';
import { ISysDailyCompOffRequestBillVm } from '/@/views/daily/sysdailycompoffrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import { commonApi } from '/@/api/common';

// 常量定义
const BILL_STATUS = {
	DRAFT: '草稿',
	FORMAL: '正文',
} as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
} as const;

const COMP_OFF_TYPE_OPTIONS = [
	{ value: '正常调休', label: '正常调休' },
	{ value: '等时调休', label: '等时调休' },
	{ value: '积分兑换', label: '积分兑换' },
] as const;

const BUTTON_TEXTS = {
	SAVE: '保存',
	SUBMIT: '提交',
	CLOSE: '关闭',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const hasSavedOnce = ref(false);
const overtimeTableRef = ref();

// 动态表单验证规则
const formRules = computed(() => {
	const rules: Record<string, any[]> = {
		'Entity.CompOffType': [{ required: true, message: '请选择调休类型', trigger: 'change' }],
		'Entity.StartTime': [{ required: true, message: '请选择开始时间', trigger: 'change' }],
		'Entity.EndTime': [{ required: true, message: '请选择结束时间', trigger: 'change' }],
		'Entity.Days': [{ required: true, message: '请输入天数', trigger: 'blur' }],
	};

	return rules;
});

const stateData = reactive<IViewModel<ISysDailyCompOffRequestBillVm>>({
	vmModel: {
		Entity: {
			ID: null,
			PersonId: null,
			OrgId: null,
			StaffNo: null,
			Name: null,
			StartTime: null,
			EndTime: null,
			Days: null,
			Reason: null,
			CompOffType: null,
			CompOffHours: null,
			Approver: null,
			ApprovalTime: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
		} as any,
		ActionName: null,
		IsMyApprove: null,
		SelectedCompOffOvertimeLinksIds: [],
	},
	AllSysGroups: [] as any[],
	prefillPerson: null as any,
});

// 加班记录表格配置
const overtimeTableData = ref<any>({
	data: [] as any[],
	header: [
		{ title: '加班单号', key: 'BillCode', type: 'text', isCheck: true, width: '140' },
		{ title: '补偿类型', key: 'CompensationType', type: 'text', isCheck: true, width: '100' },
		{ title: '姓名', key: 'Name', type: 'text', isCheck: true, width: '100' },
		{ title: '工号', key: 'StaffNo', type: 'text', isCheck: true, width: '100' },
		{ title: '开始时间', key: 'StartTime', type: 'datetime', isCheck: true, width: '150' },
		{ title: '结束时间', key: 'EndTime', type: 'datetime', isCheck: true, width: '150' },
		{ title: '加班时长(小时)', key: 'OvertimeHours', type: 'text', isCheck: true, width: '120', fixed: 'right' },
		{
			title: '已调休时长(小时)',
			key: 'UsedCompOffHours',
			type: 'text',
			isCheck: true,
			width: '140',
			fixed: 'right',
			editable: true,
			editType: 'textbox',
			placeholder: '双击输入本次使用时长',
		},
		{ title: '剩余可用时长(小时)', key: 'RemainingCompOffHours', type: 'text', isCheck: true, width: '140', fixed: 'right' },
		{ title: '事由', key: 'Reason', type: 'text', isCheck: true, width: '200' },
	],
	config: {
		total: 0,
		loading: false,
		isSerialNo: false,
		isSelection: true,
		isOperate: false, // 关闭操作列，使用双击编辑
		isBorder: true,
		hideSetting: true,
		hidePrint: true,
		hideRefresh: true,
		hideDensity: true,
		selectionFixed: 'left', // 固定多选框列在左侧
	},
});

// 日期限制：前后60天
const disabledDate = computed(() => {
	return (time: Date) => {
		const today = new Date();
		const sixtyDaysAgo = new Date(today.getTime() - 60 * 24 * 60 * 60 * 1000);
		const sixtyDaysLater = new Date(today.getTime() + 60 * 24 * 60 * 60 * 1000);
		return time < sixtyDaysAgo || time > sixtyDaysLater;
	};
});

// 计算属性
const hasEntityId = computed(() => {
	const entity = stateData.vmModel.Entity as any;
	return !!(entity && entity.ID);
});

const canSubmit = computed(() => hasEntityId.value && hasSavedOnce.value);

// 监听开始时间和结束时间变化，自动计算天数
watch(
	[() => stateData.vmModel.Entity.StartTime, () => stateData.vmModel.Entity.EndTime],
	([startTime, endTime]) => {
		if (startTime && endTime) {
			const start = new Date(startTime);
			const end = new Date(endTime);

			// 确保结束时间不早于开始时间
			if (end >= start) {
				// 计算天数差（包含开始和结束日期）
				const timeDiff = end.getTime() - start.getTime();
				const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24)) + 1;
				stateData.vmModel.Entity.Days = daysDiff.toString();
			} else {
				// 如果结束时间早于开始时间，清空天数
				stateData.vmModel.Entity.Days = null;
			}
		} else {
			// 如果任一时间为空，清空天数
			stateData.vmModel.Entity.Days = null;
		}
	},
	{ immediate: true }
);

// 统一的成功处理函数
const handleSuccess = (response: any, isSubmit = false) => {
	// 根据操作类型显示不同的消息
	if (isSubmit) {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '提交成功');
		emit('refresh');
		closeDialog();
	} else {
		ElMessage.success(ci.proxy?.$t('message._system.common.vm.savetip') || '保存成功');
		emit('refresh');
		// 保存后不关闭弹窗，更新实体ID
		if (response?.Entity?.ID) {
			stateData.vmModel.Entity = response.Entity;
		} else if (response?.ID) {
			(stateData.vmModel.Entity as any).ID = response.ID;
		}
		hasSavedOnce.value = true;
	}

	loading.value = false;
	nextTick(() => {
		setupHeaderButtons();
	});
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的API请求处理函数
const handleApiRequest = (apiCall: () => Promise<any>, beforeSubmit: () => void, isSubmit = false) => {
	other.validateFormWithMessage(formRef.value, () => {
		loading.value = true;
		beforeSubmit();
		apiCall()
			.then((response: any) => handleSuccess(response, isSubmit))
			.catch(handleError);
	});
};

// 获取当前登录人信息，默认带出申请人信息
const getCurrentPersonInfo = async () => {
	try {
		const response = await commonApi().getPersonInfo({});
		if (response && response.Data) {
			const personInfo = response.Data;
			// 设置预填充信息（用于WtmPersonSelector显示）
			stateData.prefillPerson = personInfo;
			// 设置PersonId，这样表单会有默认值
			stateData.vmModel.Entity.PersonId = personInfo.ID;
			// 填充其他相关信息
			stateData.vmModel.Entity.StaffNo = personInfo.StaffNo || '';
			stateData.vmModel.Entity.Name = personInfo.Name || '';
			stateData.vmModel.Entity.OrgId = personInfo.OrgId || '';
			stateData.vmModel.Entity.GroupId = personInfo.GroupId || '';
		}
	} catch (error) {
		console.warn('获取当前登录人信息失败:', error);
		// 失败时不影响正常使用，用户可以手动选择
	}
};

// 调休类型变化处理
const onCompOffTypeChange = async (value: string) => {
	// 清空加班记录
	overtimeTableData.value.data = [];
	stateData.vmModel.Entity.CompOffHours = null;
	stateData.vmModel.SelectedCompOffOvertimeLinksIds = [];

	// 如果选择等时调休且已选择人员，加载可用加班记录
	if (value === '等时调休' && stateData.vmModel.Entity.PersonId) {
		await loadAvailableOvertimeRecords();
	}
};

// 加载可用加班记录
const loadAvailableOvertimeRecords = async () => {
	if (!stateData.vmModel.Entity.PersonId) {
		return;
	}

	overtimeTableData.value.config.loading = true;
	try {
		const response = await api().getAvailableOvertimeForCompOff(stateData.vmModel.Entity.PersonId as string);
		// 后端返回的数据在 Data 字段中
		overtimeTableData.value.data = response.Data || response.data || [];
		overtimeTableData.value.config.total = overtimeTableData.value.data.length;

		// 初始化每行的 UsedCompOffHours 字段（本次要使用的调休时长）
		overtimeTableData.value.data.forEach((row: any) => {
			// 如果有 OvertimeUsages 数据，使用它来恢复已使用的时长（保存后继续编辑的情况）
			if (stateData.vmModel.OvertimeUsages && stateData.vmModel.OvertimeUsages[row.ID]) {
				row.UsedCompOffHours = stateData.vmModel.OvertimeUsages[row.ID];
			} else if (row.UsedCompOffHours === undefined || row.UsedCompOffHours === null) {
				row.UsedCompOffHours = 0;
			}
		});

		// 如果有 OvertimeUsages，说明是保存后继续编辑，需要恢复选中状态和总调休时长
		if (
			stateData.vmModel.OvertimeUsages &&
			stateData.vmModel.SelectedCompOffOvertimeLinksIds &&
			stateData.vmModel.SelectedCompOffOvertimeLinksIds.length > 0
		) {
			nextTick(() => {
				stateData.vmModel.SelectedCompOffOvertimeLinksIds?.forEach((id: string) => {
					const row = overtimeTableData.value.data.find((item: any) => item.ID === id);
					if (row && overtimeTableRef.value) {
						overtimeTableRef.value.toggleRowSelection(row, true);
					}
				});
			});
			calculateTotalCompOffHours();
		}
	} catch (error) {
		console.error('加载可用加班记录失败:', error);
		ElMessage.error('加载可用加班记录失败');
	} finally {
		overtimeTableData.value.config.loading = false;
	}
};

// 加班记录选择变化处理
const handleOvertimeSelectionChange = (selection: any[]) => {
	// 保存选中的加班记录ID（用于提交时筛选）
	stateData.vmModel.SelectedCompOffOvertimeLinksIds = selection.map((item: any) => item.ID);

	// 重新计算总调休时长
	calculateTotalCompOffHours();
};

// 计算总调休时长 - 根据所有已填写的已调休时长累加
const calculateTotalCompOffHours = () => {
	// 遍历所有加班记录，累加已填写的已调休时长（不管是否勾选）
	const totalHours = overtimeTableData.value.data.reduce((sum: number, item: any) => {
		const usedHours = parseFloat(item.UsedCompOffHours) || 0;
		return sum + usedHours;
	}, 0);

	stateData.vmModel.Entity.CompOffHours = totalHours > 0 ? totalHours.toString() : null;
};

// 单元格变化处理 - 验证输入的本次使用调休时长
const handleCellChange = (rowIndex: number, column: string, value: any, type: string) => {
	if (column === 'UsedCompOffHours') {
		const row = overtimeTableData.value.data[rowIndex];
		const inputValue = parseFloat(value) || 0;

		// 获取剩余可用时长（这是后端返回的可用时长）
		const remainingHours = row.RemainingCompOffHours + 3 || 0;

		// 验证：输入值不能为负数
		if (inputValue < 0) {
			ElMessage.warning('本次使用调休时长不能为负数');
			row.UsedCompOffHours = 0;
			nextTick(() => {
				calculateTotalCompOffHours();
			});
			return;
		}

		// 验证：输入值不能超过剩余可用时长
		if (inputValue > remainingHours) {
			ElMessage.warning(`本次使用时长不能超过剩余可用时长(${remainingHours}小时，最多额外超出3小时！)`);
			row.UsedCompOffHours = remainingHours;
			nextTick(() => {
				calculateTotalCompOffHours();
			});
			return;
		}

		// 更新本次使用时长
		row.UsedCompOffHours = inputValue;

		// 重新计算总调休时长
		nextTick(() => {
			calculateTotalCompOffHours();
		});
	}
};

// 人员选择变化处理
const onPersonSelected = async (value: any, person: any) => {
	if (person) {
		// 自动填充员工信息
		stateData.vmModel.Entity.StaffNo = person.StaffNo || '';
		stateData.vmModel.Entity.Name = person.Name || '';
		stateData.vmModel.Entity.OrgId = person.OrgId || '';
		stateData.vmModel.Entity.GroupId = person.GroupId || '';

		// 如果当前选择的是等时调休，加载可用加班记录
		if (stateData.vmModel.Entity.CompOffType === '等时调休') {
			await loadAvailableOvertimeRecords();
		}
	} else {
		// 清空员工信息
		stateData.vmModel.Entity.StaffNo = null;
		stateData.vmModel.Entity.Name = null;
		stateData.vmModel.Entity.OrgId = null;
		stateData.vmModel.Entity.GroupId = null;

		// 清空加班记录
		overtimeTableData.value.data = [];
		stateData.vmModel.Entity.CompOffHours = null;
		stateData.vmModel.SelectedCompOffOvertimeLinksIds = [];
	}
};

// 取消
const onClose = () => {
	closeDialog();
};

// 保存
const onSave = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝，确保新增时不发送无效的 ID 字段
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));
			if (!submitData.Entity.ID) {
				// 如果没有有效的 ID，删除该字段
				delete submitData.Entity.ID;
			}

			// 构建 OvertimeUsages 字典: Key: 加班申请单ID, Value: 使用的加班小时数
			if (stateData.vmModel.Entity.CompOffType === '等时调休') {
				const overtimeUsages: Record<string, number> = {};
				overtimeTableData.value.data.forEach((item: any) => {
					const usedHours = parseFloat(item.UsedCompOffHours) || 0;
					if (usedHours > 0) {
						overtimeUsages[item.ID] = usedHours;
					}
				});
				submitData.OvertimeUsages = overtimeUsages;
			}

			return api().add(submitData);
		},
		() => {
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.DRAFT;
		},
		false // 保存后不关闭弹窗
	);
};

// 提交
const onSubmit = () => {
	handleApiRequest(
		() => {
			// 创建一个深拷贝用于提交
			const submitData = JSON.parse(JSON.stringify(stateData.vmModel));

			// 构建 OvertimeUsages 字典: Key: 加班申请单ID, Value: 使用的加班小时数
			if (stateData.vmModel.Entity.CompOffType === '等时调休') {
				const overtimeUsages: Record<string, number> = {};
				overtimeTableData.value.data.forEach((item: any) => {
					const usedHours = parseFloat(item.UsedCompOffHours) || 0;
					if (usedHours > 0) {
						overtimeUsages[item.ID] = usedHours;
					}
				});
				submitData.OvertimeUsages = overtimeUsages;
			}

			// 提交时调用编辑接口（保存后应该已有ID）
			return api().edit(submitData);
		},
		() => {
			// 提交前设置状态
			stateData.vmModel.Entity.BillStatus = BILL_STATUS.FORMAL;
			stateData.vmModel.Entity.WorkflowStatus = WORKFLOW_STATUS.SUBMITTING;
		},
		true // 提交后关闭弹窗
	);
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	if (wtmdata?.ID) {
		(stateData.vmModel.Entity as any).ID = wtmdata.ID;
		hasSavedOnce.value = true;
	}
};

// 加载页面数据
const loadPageData = async () => {
	const API_ENDPOINTS = {
		GROUPS: '/api/SysDailyCompOffRequestBill/GetSysGroups',
	} as const;

	const [groups, billCode] = await Promise.allSettled([
		other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
		api().getBillCode(),
		getCurrentPersonInfo(), // 获取当前用户信息，默认带入
	]);

	// 处理成功的结果
	if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
	if (billCode.status === 'fulfilled') stateData.vmModel.Entity.BillCode = billCode.value.Data as string;
};

// 页面加载时
onMounted(async () => {
	loading.value = true;
	initializePageData();

	try {
		await loadPageData();
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SAVE,
			type: undefined,
			onClick: onSave,
			visible: !hasSavedOnce.value,
		},
		{
			text: BUTTON_TEXTS.SUBMIT,
			confirm: '提交单据以后无法修改，是否确认提交?',
			type: 'primary',
			onClick: onSubmit,
			visible: canSubmit.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
